package com.cqc.jdk8.Jutil;

import org.junit.Test;

import java.util.StringTokenizer;

/**
 * @author cui
 * @description StringTokenizer和split类似
 * 参考：  https://blog.csdn.net/shujuboke/article/details/76084842
 * @date 2022/5/11
 **/
public class StringTokenizerTest {

    /**
     * Java默认的分隔符是“空格”、“制表符(‘\t’)”、“换行符(‘\n’)”、“回车符(‘\r’)”。
     * 返回结果：
     * 4##a
     * 3##b
     * 2##c
     * 1##d
     */

    @Test
    public void f1() {
        String str = "a b   c d";
        StringTokenizer tokenizer = new StringTokenizer(str);
        while (tokenizer.hasMoreTokens()) {
            System.out.println(tokenizer.countTokens() + "##" + tokenizer.nextToken());
        }
    }


    /**
     * 指定分隔符 delimiter
     */
    @Test
    public void f2() {
        String str = "a,b,c,d";
        String delim = ",";
        StringTokenizer tokenizer = new StringTokenizer(str, delim);
        while (tokenizer.hasMoreTokens()) {
            System.out.println(tokenizer.countTokens() + "##" + tokenizer.nextToken());
        }

        StringTokenizer tokenizer2 = new StringTokenizer(str, delim);
        while (tokenizer2.hasMoreElements()) {
            System.out.println(tokenizer2.countTokens()  + "##" + tokenizer2.nextElement());
        }
    }

    /**
     * returnDelims:true 也返回分隔符
     * 返回结果
     * 7##a
     * 6##,
     * 5##b
     * 4##,
     * 3##c
     * 2##,
     * 1##d
     */
    @Test
    public void f3() {
        String str = "a,b,c,d";
        String delim = ",";
        StringTokenizer tokenizer = new StringTokenizer(str, delim, true);
        while (tokenizer.hasMoreTokens()) {
            System.out.println(tokenizer.countTokens()  + "##" + tokenizer.nextToken());
        }
    }
    @Test
    public void f4() {
        String str = "a+b+c+d";
        String[] arr = str.split("\\+");
        for (String s : arr) {
            System.out.println(s);
        }
    }
}
